package com.kevin.ymqquan.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.kevin.ymqquan.R;
import com.kevin.ymqquan.activity.ClubDetailActivity;
import com.kevin.ymqquan.adapter.ClubListAdapter;
import com.kevin.ymqquan.application.App;
import com.kevin.ymqquan.bean.ClubListData;
import com.kevin.ymqquan.cache.ImageLoader;
import com.kevin.ymqquan.constants.Constants;
import com.kevin.ymqquan.custom.CustomToast;
import com.kevin.ymqquan.httppost.Helper;
import com.kevin.ymqquan.httppost.HttpPostService;
import com.kevin.ymqquan.view.CommonListView;
import com.kevin.ymqquan.view.CommonListView.IXListViewListener;

public class ClubFragment extends Fragment implements OnItemClickListener,
		IXListViewListener, OnClickListener {

	public String tag = this.getClass().getSimpleName(); // tag 用于测试log用
	private App application;
	private List<ClubListData> clubList = new ArrayList<ClubListData>();
	private Dialog dialog;

	private int currPage = 1;
	ClubListAdapter clubAdapter;
	private CommonListView lv_club_list;
	private boolean isRefresh = false;

	private EditText et_club_search_text;
	private TextView tv_club_search_button;

	private boolean isFirst = true;// 判断是否为其他页返回

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
//		Log.i("kevinlog", "--++--" + "onCreateView");
		View v = inflater.inflate(R.layout.fragment_club, null);

		lv_club_list = (CommonListView) v.findViewById(R.id.lv_club_list);
		et_club_search_text = (EditText) v
				.findViewById(R.id.et_club_search_text);
		et_club_search_text.clearFocus();
		tv_club_search_button = (TextView) v
				.findViewById(R.id.tv_club_search_button);
		tv_club_search_button.setOnClickListener(this);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
//		Log.i("kevinlog", "--++--" + "onActivityCreated");
		super.onActivityCreated(savedInstanceState);
		init();
		if (Helper.checkConnection(getActivity())) {
			dialog = CustomToast.createLoadingDialog(getActivity(), "数据获取中...");
			dialog.setCancelable(true);
			dialog.show();
			ClubAsynTask policyTask = new ClubAsynTask(true);
			policyTask.execute();

		} else {
			CustomToast.CustomActivityToast(getActivity(), "网络连接异常，请检查您的网络",
					-80);
		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub

		ImageLoader imageLoader = clubAdapter.getImageLoader();
		if (imageLoader != null) {
			imageLoader.clearCache();
		}

		super.onDestroy();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		
		super.onResume();

		if (isFirst) {
			isFirst = false;
		} else {
			onRefresh();
		}
	}

	private void init() {
		application = (App) getActivity().getApplication();

		// 下拉刷新不可用
		lv_club_list.setPullLoadEnable(true);
		lv_club_list.setPullRefreshEnable(true);
		lv_club_list.setXListViewListener(this);
		lv_club_list.stopLoadMore();
		lv_club_list.stopRefresh();

		clubAdapter = new ClubListAdapter(ClubFragment.this, clubList);
		lv_club_list.setAdapter(clubAdapter);
		lv_club_list.setOnItemClickListener(ClubFragment.this);

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// TODO Auto-generated method stub
		if (position != 0) {
			Intent i = new Intent(getActivity(), ClubDetailActivity.class);
			position--;
			i.putExtra("clubId", clubList.get(position).getClubId() + "");
			i.putExtra("clubName", clubList.get(position).getClubName()
					.replace("null", ""));
			i.putExtra("clubMemberCount", clubList.get(position)
					.getClubMemberCount().replace("null", ""));
			i.putExtra("clubOwner", clubList.get(position).getClubOwner()
					.replace("null", ""));
			i.putExtra("clubOwnerPhone", clubList.get(position)
					.getClubOwnerPhone().replace("null", ""));
			i.putExtra("clubJoinDate", clubList.get(position).getClubJoinDate()
					.replace("null", ""));
			i.putExtra("clubCreateDate", clubList.get(position)
					.getClubCreateDate().replace("null", ""));
			i.putExtra("isJoin",
					clubList.get(position).getIsJoin().replace("null", ""));
			startActivity(i);
		}

	}

	class ClubAsynTask extends AsyncTask<String, Object, String> {

		private boolean dialogShow = true;

		public ClubAsynTask(boolean dialogShow) {
			// TODO Auto-generated constructor stub
			this.dialogShow = dialogShow;
		}

		@Override
		protected String doInBackground(String... params) {

			String param = "{\"method\":\"clubList\",\"userId\":\""
					+ application.userId + "\",\"pageNum\":\"" + currPage
					+ "\",\"clubSearchText\":\""
					+ et_club_search_text.getText().toString() + "\"}";

			String replyList = "";
			try {
				replyList = HttpPostService.PostJsonString(
						Constants.ServerAddr, param);
			} catch (Exception e) {
				e.printStackTrace();
			}
//			Log.i("kevinlog", "--++--" + param);
//			Log.i("kevinlog", "--++--" + replyList);
			return replyList;
		}

		@Override
		protected void onPostExecute(String JsonResult) {
			// TODO Auto-generated method stub
			super.onPostExecute(JsonResult);
			// Log.i("sssss", JsonResult);
			if (JsonResult != null) {
				// String result = JsonResult.replace("\n", "");
				String result = JsonResult;
				JSONObject jsonObject;
				try {
					jsonObject = new JSONObject(result);
					String resultType = jsonObject.getString("status");
					if ("0".equals(resultType)) {
						JSONArray jsonArray = jsonObject
								.getJSONArray("clubList");

						if (isRefresh) {
							clearList();
						}

						for (int i = 0; i < jsonArray.length(); i++) {
							JSONObject eduPolicyObject = jsonArray
									.getJSONObject(i);
							ClubListData eduPolicy = new ClubListData();
							eduPolicy.setClubName(eduPolicyObject
									.getString("clubName"));
							eduPolicy.setClubOwner(eduPolicyObject
									.getString("clubOwner"));
							eduPolicy.setClubMemberCount(eduPolicyObject
									.getString("clubMemberCount"));
							eduPolicy.setClubLogoUrl(eduPolicyObject
									.getString("clubLogoUrl"));
							eduPolicy.setIsJoin(eduPolicyObject
									.getString("isJoin"));
							eduPolicy.setClubId(Integer
									.parseInt(eduPolicyObject
											.getString("clubId")));
							eduPolicy.setClubOwnerPhone(eduPolicyObject
									.getString("clubOwnerPhone"));
							eduPolicy.setClubCreateDate(eduPolicyObject
									.getString("clubCreateDate"));
							eduPolicy.setClubJoinDate(eduPolicyObject
									.getString("clubJoinDate"));
							// if (!clubList.contains(eduPolicy))
							clubList.add(eduPolicy);
						}

						clubAdapter.notifyDataSetChanged();

						if (dialogShow) {
							dialog.dismiss();
						}
					} else {
						if (dialogShow) {
							dialog.dismiss();
						}
						CustomToast.CustomActivityToast(getActivity(), "没有更多了",
								-80);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					if (dialogShow) {
						dialog.dismiss();
					}
					CustomToast
							.CustomActivityToast(getActivity(), "没有更多了", -80);
					e.printStackTrace();
				}

				lv_club_list.stopLoadMore();
				lv_club_list.stopRefresh();
			} else {
				if (dialogShow) {
					dialog.dismiss();
				}
				CustomToast.CustomActivityToast(getActivity(), "网络异常请稍后重试！",
						-80);

			}
		}
	}

	@Override
	public void onRefresh() {
		// clearList();
		currPage = 1;
		isRefresh = true;
		ClubAsynTask policyTask = new ClubAsynTask(false);
		policyTask.execute();

	}

	@Override
	public void onLoadMore() {
		isRefresh = false;
		++currPage;
		ClubAsynTask policyTask = new ClubAsynTask(false);
		policyTask.execute();
	}

	public void clearList() {
		currPage = 1;
		clubList.clear();
		clubAdapter.notifyDataSetChanged();

	}

	@Override
	public void onClick(View v) {
		onRefresh();
	}

}
